<template>
  <div class="AiChat" >
    <div class="chatInfo">
      <el-scrollbar style="height:100%;" ref="scrollCC">
        <div v-for="(item, index) in dialogueHistory" :key="index">
          <div class="chatitem userItem" v-if="item.role === 'user'">
            <div class="imgUser"><img :src="aiimg2" alt="" title="" /></div>
            <div class="content">
              <pre style="white-space: pre-wrap; ">{{item.content}}</pre>
              <i class="u-copy el-icon-document-copy" title="复制" @click="copy(item.content)"/>
            </div>
          </div>
          <div class="chatitem assistantItem" v-if="item.role === 'assistant'">
            <div class="imgUser"><img :src="aiimg1" alt="" title="" /></div>
            <div class="content">
              <pre style="white-space: pre-wrap; ">{{item.content}}</pre>
              <i class="u-copy el-icon-document-copy" title="复制" @click="copy(item.content)"/>
            </div>
          </div>
        </div>
        <div class="chatitem assistantItem" v-if="isWait">
          <div class="imgUser"><img :src="aiimg1" alt="" title="" /></div>
          <div class="content">
            <div class="ball-beat">
              <div></div>
              <div></div>
              <div></div>
            </div>
          </div>
        </div>
      </el-scrollbar>
    </div>
    <div class="formChat">
      <el-form :label-width="'0px'" @submit.native.prevent>
        <el-form-item>
          <el-input type="textarea" size="mini"
            v-model="form.text" maxlength="2000" :rows="3" placeholder="输入消息..." @keyup.ctrl.enter.native="save">
          </el-input>
        </el-form-item>
      </el-form>
      <div class="btn-submit">
        <el-button size="small" type="primary" @click="save" :disabled="isWait">发送（Ctrl+Enter）</el-button>
      </div>
    </div>
  </div>
</template>
<script>
import aiimg1 from '@/assets/ai1.jpg'
import aiimg2 from '@/assets/ai2.png'
export default {
  props: {
    dialogue: {
      type: Object
    },
    usedNumGet: {
      type: Function
    }
  },
  created () {
    this.dialogueHistory = this.dialogue.history ? JSON.parse(JSON.stringify(this.dialogue.history)) : []
  },
  mounted () {
    this.$nextTick(() => {
      this.$refs['scrollCC'].wrap.scrollTop = this.$refs['scrollCC'].wrap.scrollHeight
    })
  },
  data () {
    return {
      aiimg1: aiimg1,
      aiimg2: aiimg2,
      form: {
        text: ''
      },
      dialogueHistory: [],
      // 是否正在等待回复
      isWait: false
    }
  },
  watch: {
    dialogue (val) {
      this.dialogueHistory = val.history ? JSON.parse(JSON.stringify(val.history)) : []
      this.$nextTick(() => {
        this.$refs['scrollCC'].wrap.scrollTop = this.$refs['scrollCC'].wrap.scrollHeight
      })
    }
  },
  methods: {
    save () {
      if (this.isWait || this.form.text.trim() === '') {
        return
      }
      this.isWait = true
      let userText = {
        role: 'user',
        content: this.form.text.trim()
      }
      this.dialogueHistory.push(userText)
      this.$nextTick(() => {
        this.$refs['scrollCC'].wrap.scrollTop = this.$refs['scrollCC'].wrap.scrollHeight
      })
      // AI创作对话
      this.$post('/ai/ai-text-dialogue', {message: this.form.text.trim()}).then(response => {
        if (response) {
          if (response.dialogue && response.dialogue.history) {
            this.dialogueHistory = response.dialogue.history
          }
          this.usedNumGet()
          this.isWait = false
          this.form.text = ''
          this.$nextTick(() => {
            this.$refs['scrollCC'].wrap.scrollTop = this.$refs['scrollCC'].wrap.scrollHeight
          })
        } else {
          this.isWait = false
        }
      })
    },
    copy (copyText) {
      const input = document.createElement('textarea')
      document.body.appendChild(input)
      input.innerHTML = copyText
      input.setAttribute('code', 1)
      input.select()
      if (navigator.clipboard !== undefined) { // Chrome
        navigator.clipboard.writeText(copyText).then(() => {
          this.$message.success('复制成功！')
        }, function (err) {
          console.error('Async: Could not copy text: ', err)
        })
      } else if (window.clipboardData) { // Internet Explorer
        window.clipboardData.setData('Text', copyText)
        this.$message.success('复制成功！')
      } else {
        document.execCommand('Copy')
        let list = document.getElementsByTagName('textarea')
        let inputList = Array.prototype.slice.call(list)
        inputList.forEach((item) => {
          if (item.getAttribute('code')) {
            document.body.removeChild(item)
          }
        })
        this.$message.success('复制成功！')
      }
    }
  },
  components: {
  }
}
</script>
<style scoped lang="scss">
.AiChat{
  padding-bottom: 100px;
  position: relative;
  /deep/ {
    .el-scrollbar__wrap {
      overflow-x: hidden;
    }
    .is-horizontal{
      display: none;
    }
  }
  .chatInfo{
    height: calc(100vh - 240px);
  }
  .formChat{
    position: absolute;
    left: 0;
    width: 100%;
    bottom: 0;
    padding-top: 10px;
    border-top: 1px solid #e0e0e0;
    background: #fff;
    /deep/ .el-form-item{
      margin-bottom: 0;
    }
    /deep/ .el-textarea__inner{
      padding-bottom: 30px;
      font-size: 13px;
    }
  }
  .btn-submit{
    position: absolute;
    right: 0;
    bottom: 0;
  }
}
.chatitem {
  margin-bottom: 20px;
  overflow: hidden;
  display: flex;
  width: 100%;
  justify-content: flex-start;
  align-items: flex-start;
  .imgUser{
    width: 42px;
    height: 42px;
    border-radius: 3px;
    img {
      max-height: 100%;
      max-width: 100%;
    }
  }
  .content{
    padding: 12px 20px 11px;
    max-width: calc(100% - 56px);
    margin-right: 12px;
    position: relative;
    border-radius: 3px;
    &:before{
      content: '';
      position: absolute;
    }
    .u-copy{
      position: absolute;
      top: 0;
      right: 0;
      padding: 5px;
      display: none;
      cursor: pointer;
      &:hover{
        background: #52A7FC;
        color: #fff;
      }
    }
    &:hover .u-copy{
      display: block;
    }
  }
}
.userItem{
  flex-direction: row-reverse;
  .content{
    background: #258FFB;
    color: #fff;
    &:before{
      right: -14px;
      border-top: 7px solid transparent;
      border-left: 7px solid #258FFB;
      border-bottom: 7px solid transparent;
      border-right: 7px solid transparent;
    }
    .u-copy{
      left: 0;
      right: auto;
    }
  }
}
.assistantItem{
  .imgUser{
    background: #ddd;
  }
  .content{
    background: #f6f6f6;
    color: #333;
    margin-right: 0;
    margin-left: 12px;
    &:before{
      left: -14px;
      border-top: 7px solid transparent;
      border-left: 7px solid transparent;
      border-bottom: 7px solid transparent;
      border-right: 7px solid #f6f6f6;
    }
  }
}
@-webkit-keyframes ball-beat {
        50% {
                opacity: 0.2;
                -webkit-transform: scale(0.75);
                transform: scale(0.75);
        }

        100% {
                opacity: 1;
                -webkit-transform: scale(1);
                transform: scale(1);
        }
}

@keyframes ball-beat {
        50% {
                opacity: 0.2;
                -webkit-transform: scale(0.75);
                transform: scale(0.75);
        }

        100% {
                opacity: 1;
                -webkit-transform: scale(1);
                transform: scale(1);
        }
}

.ball-beat>div {
        background-color: #bbb;
        width: 8px;
        height: 8px;
        border-radius: 100%;
        margin: 4px 2px;
        -webkit-animation-fill-mode: both;
        animation-fill-mode: both;
        display: inline-block;
        -webkit-animation: ball-beat 0.7s 0s infinite linear;
        animation: ball-beat 0.7s 0s infinite linear;
}

.ball-beat>div:nth-child(2n-1) {
        -webkit-animation-delay: 0.35s !important;
        animation-delay: 0.35s !important;
}
</style>
